package com.ak.server.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import com.ak.common.utils.StringUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ak.common.annotation.LogEndpoint;
import com.ak.common.controller.BaseController;
import com.ak.common.entity.AKResponse;
import com.ak.common.entity.QueryRequest;
import com.ak.common.entity.system.SystemUser;
import com.ak.common.exception.AKException;
import com.ak.common.utils.AKUtil;
import com.ak.server.log.entity.LoginLog;
import com.ak.server.log.service.ILoginLogService;
import com.ak.server.system.service.IUserService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;

/**
 * @author Vean
 */
@Api(tags = "用户模块")
@Validated
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController extends BaseController {

    private final IUserService userService;
    private final ILoginLogService loginLogService;
    private final PasswordEncoder passwordEncoder;

    @GetMapping("success")
    public void loginSuccess(HttpServletRequest request) {
        String currentUsername = AKUtil.getCurrentUsername();
        // update last login time
        this.userService.updateLoginTime(currentUsername);
        // save login log
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(currentUsername);

        loginLog.setUa(StringUtil.sub(request.getHeader("user-agent"), 0, 500));

        this.loginLogService.saveLoginLog(loginLog);
    }

    @GetMapping("index")
    public AKResponse index() {
        Map<String, Object> data = new HashMap<String, Object>(5);
        // 获取系统访问记录
        Long totalVisitCount = loginLogService.findTotalVisitCount();
        data.put("totalVisitCount", totalVisitCount);
        Long todayVisitCount = loginLogService.findTodayVisitCount();
        data.put("todayVisitCount", todayVisitCount);
        Long todayIp = loginLogService.findTodayIp();
        data.put("todayIp", todayIp);
        // 获取近期系统访问记录
        List<Map<String, Object>> lastTenVisitCount = loginLogService.findLastTenDaysVisitCount(null);
        data.put("lastTenVisitCount", lastTenVisitCount);
        SystemUser param = new SystemUser();
        param.setUsername(AKUtil.getCurrentUsername());
        List<Map<String, Object>> lastTenUserVisitCount = loginLogService.findLastTenDaysVisitCount(param);
        data.put("lastTenUserVisitCount", lastTenUserVisitCount);

        data.put("browserCount", loginLogService.findByBrowser());
        data.put("operatingSystemCount", loginLogService.findBySystem());
        return new AKResponse().data(data);
    }
    
    /**
     * 获取当前用户信息
     */
    @ApiOperation("获取当前登录用户")
    @GetMapping("user")
    public Map<String, Object> currentUser() {
        Map<String, Object> map = new HashMap<String, Object>(5);
        map.put("currentUser", AKUtil.getCurrentUser());
        map.put("currentUsername", AKUtil.getCurrentUsername());
        map.put("currentUserAuthority", AKUtil.getCurrentUserAuthority());
        map.put("currentTokenValue", AKUtil.getCurrentTokenValue());
        map.put("currentRequestIpAddress", AKUtil.getHttpServletRequestIpAddress());
        return map;
    }

    @ApiOperation("获取用户集合")
    @GetMapping
    @PreAuthorize("hasAuthority('user:view')")
    public AKResponse userList(QueryRequest queryRequest, SystemUser user) {
        Map<String, Object> dataTable = AKUtil.getDataTable(userService.findUserList(user, queryRequest));
        return new AKResponse().data(dataTable);
    }

    @ApiOperation("检查用户名是否存在")
    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
        return this.userService.findByName(username) == null;
    }

    @ApiOperation("添加用户")
    @PostMapping
    @PreAuthorize("hasAuthority('user:add')")
    @LogEndpoint(operation = "新增用户", exceptionMessage = "新增用户失败")
    public void addUser(@Valid SystemUser user) {
    	// 租户管理员新增角色，所以用户的租户编码为当前登录用户的租户编码
    	user.setCreateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        this.userService.createUser(user);
    }

    @ApiOperation("修改用户信息")
    @PutMapping
    @PreAuthorize("hasAuthority('user:update')")
    @LogEndpoint(operation = "修改用户", exceptionMessage = "修改用户失败")
    public void updateUser(@Valid SystemUser user) {
    	user.setUpdateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        this.userService.updateUser(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userIds}")
    @PreAuthorize("hasAuthority('user:delete')")
    @LogEndpoint(operation = "删除用户", exceptionMessage = "删除用户失败")
    public void deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) {
        String[] ids = userIds.split(StringPool.COMMA);
        this.userService.deleteUsers(ids);
    }

    @ApiOperation("修改个人信息")
    @PutMapping("profile")
    @LogEndpoint(exceptionMessage = "修改个人信息失败")
    public void updateProfile(@Valid SystemUser user) throws AKException {
    	user.setUpdateBy(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        this.userService.updateProfile(user);
    }

    @PutMapping("avatar")
    @LogEndpoint(exceptionMessage = "修改头像失败")
    public void updateAvatar(@NotBlank(message = "{required}") String avatar) {
        this.userService.updateAvatar(avatar);
    }

    @GetMapping("password/check")
    public boolean checkPassword(@NotBlank(message = "{required}") String password) {
        String currentUsername = AKUtil.getCurrentUsername();
        SystemUser user = userService.findByName(currentUsername);
        return user != null && passwordEncoder.matches(password, user.getPassword());
    }

    @PutMapping("password")
    @LogEndpoint(exceptionMessage = "修改密码失败")
    public void updatePassword(@NotBlank(message = "{required}") String password) {
        userService.updatePassword(password);
    }

    @ApiOperation("重置用户密码")
    @PutMapping("password/reset")
    @PreAuthorize("hasAuthority('user:reset')")
    @LogEndpoint(exceptionMessage = "重置用户密码失败")
    public void resetPassword(@NotBlank(message = "{required}") String usernames) {
        String[] usernameArr = usernames.split(StringPool.COMMA);
        this.userService.resetPassword(usernameArr);
    }

    @ApiOperation("导出用户数据")
    @PostMapping("excel")
    @PreAuthorize("hasAuthority('user:export')")
    @LogEndpoint(operation = "导出用户数据", exceptionMessage = "导出Excel失败")
    public void export(QueryRequest queryRequest, SystemUser user, HttpServletResponse response) {
        List<SystemUser> users = this.userService.findUserList(user, queryRequest).getRecords();
        ExcelKit.$Export(SystemUser.class, response).downXlsx(users, false);
    }
}
